<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>隔离存储测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        button {
            margin: 5px;
            padding: 8px 15px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        .output {
            background: #f8f9fa;
            padding: 10px;
            margin: 10px 0;
            border-radius: 3px;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
    <h1>隔离存储功能测试</h1>
    
    <div class="test-section">
        <h3>用户模拟登录</h3>
        <button onclick="loginUser1()">模拟用户1登录</button>
        <button onclick="loginUser2()">模拟用户2登录</button>
        <button onclick="logout()">登出</button>
    </div>
    
    <div class="test-section">
        <h3>数据操作</h3>
        <button onclick="setData()">设置数据</button>
        <button onclick="getData()">获取数据</button>
        <button onclick="clearData()">清理当前用户数据</button>
        <button onclick="clearAllData()">清理所有数据</button>
    </div>
    
    <div class="test-section">
        <h3>存储状态</h3>
        <button onclick="showStorageStatus()">显示存储状态</button>
        <div id="output" class="output"></div>
    </div>

    <script type="module">
        // 模拟隔离存储类
        class IsolatedStorage {
            constructor() {
                this.prefix = 'app_';
                this.currentUserId = null;
                this.sessionId = this.generateSessionId();
            }

            generateSessionId() {
                return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            }

            getStorageKey(key) {
                if (this.currentUserId) {
                    return `${this.prefix}user_${this.currentUserId}_${key}`;
                } else {
                    return `${this.prefix}${this.sessionId}_${key}`;
                }
            }

            setItem(key, value) {
                const storageKey = this.getStorageKey(key);
                localStorage.setItem(storageKey, value);
                this.log(`设置数据: ${storageKey} = ${value}`);
            }

            getItem(key) {
                const storageKey = this.getStorageKey(key);
                const value = localStorage.getItem(storageKey);
                this.log(`获取数据: ${storageKey} = ${value}`);
                return value;
            }

            removeItem(key) {
                const storageKey = this.getStorageKey(key);
                localStorage.removeItem(storageKey);
                this.log(`删除数据: ${storageKey}`);
            }

            setUserInfo(userInfo) {
                this.currentUserId = userInfo.id;
                this.setItem('userInfo', JSON.stringify(userInfo));
                this.log(`用户登录: ${userInfo.name} (ID: ${userInfo.id})`);
            }

            getUserInfo() {
                const userInfoStr = this.getItem('userInfo');
                if (userInfoStr) {
                    try {
                        return JSON.parse(userInfoStr);
                    } catch (error) {
                        this.log('解析用户信息失败: ' + error.message);
                        return null;
                    }
                }
                return null;
            }

            logout() {
                if (this.currentUserId) {
                    this.clearUserData(this.currentUserId);
                    this.currentUserId = null;
                }
                this.sessionId = this.generateSessionId();
                this.log('用户已登出');
            }

            clearUserData(userId) {
                const keys = Object.keys(localStorage);
                const userPrefix = `${this.prefix}user_${userId}_`;
                keys.forEach(key => {
                    if (key.startsWith(userPrefix)) {
                        localStorage.removeItem(key);
                        this.log(`清理用户数据: ${key}`);
                    }
                });
            }

            clearAll() {
                const keys = Object.keys(localStorage);
                keys.forEach(key => {
                    if (key.startsWith(this.prefix)) {
                        localStorage.removeItem(key);
                    }
                });
                this.currentUserId = null;
                this.sessionId = this.generateSessionId();
                this.log('所有数据已清理');
            }

            log(message) {
                console.log(`[IsolatedStorage] ${message}`);
                const output = document.getElementById('output');
                if (output) {
                    output.textContent += `${new Date().toLocaleTimeString()} - ${message}\n`;
                    output.scrollTop = output.scrollHeight;
                }
            }

            getStorageStatus() {
                const keys = Object.keys(localStorage);
                const appKeys = keys.filter(key => key.startsWith(this.prefix));
                return {
                    currentUserId: this.currentUserId,
                    sessionId: this.sessionId,
                    totalKeys: keys.length,
                    appKeys: appKeys.length,
                    appData: appKeys.map(key => ({
                        key,
                        value: localStorage.getItem(key)
                    }))
                };
            }
        }

        // 创建全局实例
        window.isolatedStorage = new IsolatedStorage();

        // 测试函数
        window.loginUser1 = function() {
            window.isolatedStorage.setUserInfo({
                id: 'user001',
                name: '张三',
                email: 'zhangsan@example.com'
            });
        };

        window.loginUser2 = function() {
            window.isolatedStorage.setUserInfo({
                id: 'user002',
                name: '李四',
                email: 'lisi@example.com'
            });
        };

        window.logout = function() {
            window.isolatedStorage.logout();
        };

        window.setData = function() {
            window.isolatedStorage.setItem('accessToken', 'token_' + Date.now());
            window.isolatedStorage.setItem('testData', '这是测试数据_' + Math.random());
        };

        window.getData = function() {
            const token = window.isolatedStorage.getItem('accessToken');
            const testData = window.isolatedStorage.getItem('testData');
            const userInfo = window.isolatedStorage.getUserInfo();
            
            window.isolatedStorage.log(`当前数据:\n- Token: ${token}\n- 测试数据: ${testData}\n- 用户信息: ${JSON.stringify(userInfo)}`);
        };

        window.clearData = function() {
            if (window.isolatedStorage.currentUserId) {
                window.isolatedStorage.clearUserData(window.isolatedStorage.currentUserId);
            } else {
                window.isolatedStorage.log('当前无登录用户，无法清理用户数据');
            }
        };

        window.clearAllData = function() {
            window.isolatedStorage.clearAll();
        };

        window.showStorageStatus = function() {
            const status = window.isolatedStorage.getStorageStatus();
            window.isolatedStorage.log(`存储状态:\n${JSON.stringify(status, null, 2)}`);
        };

        // 初始化显示
        window.isolatedStorage.log('隔离存储测试页面已加载');
        window.showStorageStatus();
    </script>
</body>
</html>